//authorize.js
const app = getApp()
let baseUrl = app.http.getBaseUrl(); //请求根地址
Component({
    /**
     * 组件的属性列表
     */
    properties: {

    },

    /**
     * 组件的初始数据
     */
    data: {
        hasAuth: false
    },

    /**
     * 组件的方法列表
     */
    methods: {
        getUser(res) {
            const info = res.detail
            if (info.errMsg === "getUserInfo:ok") {
                let data = {
                    "Encrypted-Data": info.encryptedData,
                    "Iv": info.iv,
                    "Code": this.code,
                    "sid": wx.getStorageSync('sid')
                }
                this.saveInfo(data)
            }
        },
        saveInfo(data) {
            app.http.post('authorize/info', {
                header: data
            }).then(res => {
                wx.setStorage({
                    key: 'user',
                    data: {
                        head_image: res.data.head_image,
                        nickname: res.data.nickname,
                    },
                    success: res => {
                        this.setData({
                            hasAuth: true,
                        })
                        let page = getCurrentPages()
                        let currentPage = page[page.length - 1]
                        currentPage.setData({
                            user: wx.getStorageSync('user')
                        })
                    }
                })
            }).catch(err => {
                wx.removeStorageSync('user')
            })
        }
    },

    attached() {
        app.toPromise(wx.login).then(res => {
            this.code = res.code
        })
        let user = wx.getStorageSync('user');
        if (user) {
            this.setData({
                hasAuth: true,
            })
        } else {
            app.toPromise(wx.getSetting).then(res => {
                if (res.authSetting['scope.userInfo']) {
                    wx.getUserInfo({
                        success: res => {
                            let data = {
                                "Encrypted-Data": res.encryptedData,
                                "Iv": res.iv,
                                "Code": this.code,
                                "sid": wx.getStorageSync('sid')
                            }
                            this.saveInfo(data)
                        }
                    })
                } else {
                    this.setData({
                        hasAuth: false,
                    })
                }
            })
        }
    },
})